## @@ ** 简单的日志记录 ** @@ ##
import os
import logging
from logging.handlers import RotatingFileHandler

from app.core.config import settings

CONFIG_PATH = os.path.join(settings.LOG_DIR, "app.log")

def setup_logger(name=__name__, level=logging.INFO, log_file=None):
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.propagate = False

    if not logger.handlers:
        formatter = logging.Formatter(
            "[%(asctime)s] [%(levelname)s] [%(module)s.%(funcName)s:%(lineno)d] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )

        # 控制台输出
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
  
        log_file = CONFIG_PATH
        # 文件输出（UTF-8）
        if log_file:
            log_dir = os.path.dirname(log_file)
            os.makedirs(log_dir, exist_ok=True)
            ## 大小、数量限制，超过备份数、自动清理
            file_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5, encoding='utf-8')
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)

    return logger

logger = setup_logger()